<script setup name="user">
import { useRepassword } from "@/composables/useManager"
import { useInitTable, useInitForm } from "@/composables/useCommon"
import { getUserList, updateUserStatus, createUser, updateUser, deleteUser } from "@/api/user"
import FormDialog from "@/components/FormDialog.vue"
import ChooseImage from "@/components/ChooseImage.vue"
import Search from "@/components/Search.vue"
import SearchItem from "@/components/SearchItem.vue"
import ListHeader from "@/components/ListHeader.vue"

// 解构公用方法
const { windowHeight, searchForm, tableData, loading, currentPage, total, limit, circleUrl, resetSearchForm, getData, handleDelete, handleStatusChange } = useInitTable({
  searchForm: {
    keyword: "",
    user_level_id: null,
    user_level: []
  },
  getList: getUserList,
  updateStatus: updateUserStatus,
  delete: deleteUser,
  onGetList: res => {
    tableData.value = res.list.map(ope => {
      ope.statusLoading = false
      return ope
    })
    total.value = res.totalCount
    // user_level.value = res.user_level
    searchForm.user_level = res.user_level
  }
})

// 解构表单公共方法
const { form, dialogRef, formRef, rules, dialogTitle, handleSubmit, handleCreate, handleEdit, resetForm } = useInitForm({
  getData,
  updata: updateUser,
  create: createUser,
  form: {
    username: "",
    password: null,
    nickname: "",
    avatar: "",
    user_level_id: null,
    status: 1,
    phone: "",
    email: ""
  },
  rules: {
    username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
    password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
    nickname: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
    user_level_id: [{ required: true, message: "用户等级为必选项", trigger: "blur" }],
    avatar: [{ required: true, message: "用户头像不能为空", trigger: "blur" }],
    phone: [
      { required: true, message: "用户手机号不能为空", trigger: blur },
      { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号格式", trigger: "blur" }
    ],
    email: [
      { required: true, message: "邮箱不能为空", trigger: "blur" },
      { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/i, message: "请输入正确的邮箱格式", trigger: "blur" }
    ],
    status: [{ required: true, trigger: "blur" }]
  }
})

// 获取仓库数据
const { user } = useRepassword()
// 减去头部高度、标签高度、内边距高度
let h = windowHeight.value - 146
const h2 = windowHeight.value - 64 - 44 - 150
</script>

<template>
  <el-card shadow="never" :body-style="{ 'padding-bottom': '10px', 'padding-left': '0', 'padding-right': '0' }"
    :style="{ height: `${h}px` }">
    <Search @search="getData" @reset="resetSearchForm">
      <SearchItem label="关键词">
        <el-input v-model="searchForm.keyword" placeholder="手机号/邮箱/会员昵称" clearable />
      </SearchItem>
      <template #show>
        <SearchItem label="会员等级">
          <el-select v-model="searchForm.user_level_id" placeholder="请选择会员等级" clearable>
            <el-option v-for="item in searchForm.user_level" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </SearchItem>
      </template>
    </Search>

    <ListHeader @create="handleCreate" @refresh="getData" />

    <div class="card-table" :style="{ height: `${h2}px` }">
      <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
        <el-table-column label="会员" align="center" min-width="160" fixed>
          <template #default="{ row }">
            <div class="avatar">
              <el-avatar :size="40" :src="row.avatar" fit="cover">
                <img :src="circleUrl">
              </el-avatar>
              <div class="avatar-info">
                <h6>{{ row.username }}</h6>
                <small>ID: {{ row.id }}</small>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="会员等级" align="center">
          <template #default="{ row }">
            {{ row.user_level?.name || "-" }}
          </template>
        </el-table-column>

        <el-table-column label="登录注册" align="center" width="234">
          <template #default="{ row }">
            <p v-if="row.last_login_time">最后登录 : {{ row.last_login_time }}</p>
            <p>注册时间 :{{ row.create_time }}</p>
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center">
          <template #default="{ row }">
            <el-switch v-model="row.status" size="small" :active-value="1" :inactive-value="0"
              :loading="row.statusLoading" :disabled="row.super === 1 || row.id === user.id"
              style="--el-switch-on-color: #13ce66" @change="handleStatusChange($event, row)" />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="80" align="center">
          <template #default="{ row }">
            <small v-if="row.super === 1">暂无操作</small>
            <div v-else>
              <el-icon @click="handleEdit(row)">
                <Edit />
              </el-icon>
              <el-popconfirm v-if="row.id !== user.id" width="186" title="是否要删除改管理员？" confirmButtonText="确认"
                cancelButtonText="取消" @confirm="handleDelete(row.id)">
                <template #reference>
                  <el-icon>
                    <CloseBold />
                  </el-icon>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据" :image-size="200" />
        </template>
      </el-table>

      <div class="user-pagination">
        <el-pagination background small layout="prev, pager, next" :total="total" :current-page="currentPage"
          :page-size="limit" :hide-on-single-page="total < 11" @current-change="getData" />
      </div>
    </div>

    <FormDialog ref="dialogRef" :width="50" :title="dialogTitle" @submit="handleSubmit" @close="resetForm">
      <el-form :model="form" ref="formRef" :rules="rules" label-width="94">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="用户名" clearable />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" clearable show-password />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入用户昵称" clearable />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <ChooseImage v-model="form.avatar" />
        </el-form-item>
        <el-form-item label="会员等级" prop="user_level_id">
          <el-select v-model="form.user_level_id" placeholder="选择会员等级">
            <el-option v-for="item in user_level" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" :active-value="1" style="--el-switch-on-color: #13ce66" :inactive-value="0" />
        </el-form-item>
      </el-form>
    </FormDialog>
  </el-card>
</template>

<style lang="scss" scoped>
.el-card {
  border: 0;
  overflow-y: auto;

  .el-select {
    width: 100%;
  }

  .searchForm {
    padding: 0 10px;

    .el-row {
      align-items: center;

      .el-col:last-child {
        display: flex;
        justify-content: end;
      }

      .refresh-form {
        display: flex;
        justify-content: space-between;
      }
    }
  }

  .user-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    margin-bottom: 10px;
  }

  .card-table {
    display: flex;
    justify-content: space-between;
    flex-direction: column;

    .el-table {
      z-index: 0;

      .avatar {
        display: flex;
        align-items: center;
        padding-left: 2vw;
        text-align: left;

        &-info {
          margin-left: 2vw;
        }
      }

      .el-icon {
        cursor: pointer;
        margin: 0 8px;

        &:last-child {
          margin-right: 0;
        }
      }
    }

    .user-pagination {
      display: flex;
      justify-content: center;
      padding-top: 10px;
    }
  }

  .but-form {
    .el-button {
      margin: 2px;

      .el-icon {
        color: var(--white);
      }
    }
  }

  :deep(.choose-dialog) {
    .el-dialog__body {
      padding: 0;
    }
  }
}

@media screen and (max-width: 375px),
screen and (max-width: 414px) {
  :deep(.el-dialog--center) {
    min-width: 80% !important;
    max-width: 80% !important;
  }

  .searchForm {
    padding: 0 10px;
  }

  .card-table {
    .el-table {
      .el-icon {
        margin: 0 4px !important;

        &:last-child {
          margin-right: 0;
        }
      }
    }

    .manager-pagination {
      display: flex;
      justify-content: center;
      padding-top: 10px;
    }
  }
}
</style>
